package readers;


/**
 * Handles the grabing of tokens in the query string
 * @author Chris
 */
public class QueryStringHandler {
    private String qString; //Holds the query string
    public QueryStringHandler(String queryString) {
        qString = queryString;
    }
    
    public void setQueryString(String queryString) {
        qString = queryString;
    }
    
    public String getQueryString() {
        return qString;
    }
    
    //Returns "" in the event no element of that name is found
    public String getElement(String element) {
        if(qString == null) {
            qString = "";
        }
        qString = qString.trim();
        int index = qString.indexOf(element);
        
        if(index == -1 || index > 0) { //Match a full case instead of a partial
            index = qString.indexOf("&" + element);
        }
        if(index == -1) {
            return null;
        }
        
        index = qString.indexOf("=", index);

        if(index == -1) {
            return null;
        }
        index++;
        String res;
        int endIndex = qString.indexOf("&", index);
        
        if(endIndex == -1) {
            endIndex = qString.length();
        }
        
        res = qString.substring(index, endIndex);
        
        if(res.contains("&") || res.contains("=")) {
            return null;
        }
        
        return res.replaceAll("\"", "");
    }
}
